
#import "FAMHttpTool.h"

#define kTimeoutInterval 60;
#if DEBUG
    NSString *FAMBaseUrl = @"http://tbcal.preproduce.net/";
    NSString *FAMUpLoadImageUrl = @"http://tbup.preproduce.net/";
#else
    NSString *FAMBaseUrl = @"https://cal.cameracalctr.com/";
    NSString *FAMUpLoadImageUrl = @"https://up.cameracalctr.com/";
#endif





static NSString *foodmateUserdata = @"foodmate/userdata";
static NSString *foodmateSuggest = @"foodmate/cate/suggest";
static NSString *getFoodmateUserdata = @"foodmate/userdata";
static NSString *putFoodmateUserdata = @"foodmate/userdata";
static NSString *getFoodmateFoodrecord = @"foodmate/foodrecord";
static NSString *postFoodmateFoodrecord = @"foodmate/foodrecord";
static NSString *deleteFoodmateFoodrecord = @"foodmate/foodrecord";
static NSString *getFoodmateStatistics = @"foodmate/statistics";
static NSString *foodmateUpload = @"foodmate/upload";
static NSString *foodIdentify = @"foodmate/food/identify";
static NSString *foodReidentify = @"foodmate/food/reidentify";
static NSString *foodRecordBatch = @"foodmate/foodrecord/batch";
static NSString *putFoodmateFoodrecord = @"foodmate/foodrecord";

@interface FAMHttpTool()<NSURLSessionDelegate>
@property (nonatomic, strong)NSString *tempNowTime;
@end
@implementation FAMHttpTool
+ (void)FAM_PostFoodmateFoodRecordBatchWithParameters:(NSMutableDictionary * __nullable)parameters success:(void(^)(FAMFoodIdentifyModel *,NSString *))success failure:(FailureBlock)failure {
    [[self alloc]FAM_postUrl:foodRecordBatch parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodIdentifyModel mj_objectWithKeyValues:@{@"foodList":requestDic}],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_PostFoodReidentifyWithParameters:(NSMutableDictionary * __nullable)parameters success:(void(^)(FAMFoodIdentifyModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_postUrl:foodReidentify parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodIdentifyModel mj_objectWithKeyValues:@{@"foodList":requestDic}],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_PostFoodIdentifyWithParameters:(NSMutableDictionary * __nullable)parameters success:(void(^)(FAMFoodIdentifyModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_postUrl:foodIdentify parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodIdentifyModel mj_objectWithKeyValues:@{@"foodList":requestDic}],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_UploadImageWithFile:(UIImage *)fileImage success:(void(^)(FAMFoodmateUploadModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_uploadUrl:foodmateUpload parameters:fileImage success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodmateUploadModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_GetFoodmateStatisticsWithData:(NSString *)beginAndEndDate success:(void(^)(FAMFoodmateStatisticsModel *,NSString *))success failure:(FailureBlock)failure {
    [[self alloc]FAM_getUrl:getFoodmateStatistics parameters:nil success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodmateStatisticsModel mj_objectWithKeyValues:@{@"cateList":requestDic}],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    } targetType:beginAndEndDate];
}
+ (void)FAM_DeleteFoodmateFoodrecordWithId:(NSString *)ids success:(void(^)(FAMFoodmateUserdataModel *,NSString *))success failure:(FailureBlock)failure {
    [[self alloc]FAM_deleteUrl:deleteFoodmateFoodrecord parameters:ids success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodmateUserdataModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_PostFoodmateFoodrecordWithParameters:(NSMutableDictionary * __nullable)parameters success:(void(^)(FAMFoodrecordModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_postUrl:postFoodmateFoodrecord parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodrecordModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_PutFoodmateFoodrecordWithParameters:(NSMutableDictionary *)parameters success:(void (^)(FAMFoodrecordModel * _Nonnull, NSString * _Nonnull))success failure:(FailureBlock)failure {
    [[self alloc]FAM_putUrl:putFoodmateFoodrecord parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodrecordModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_GetFoodmateFoodrecordWithDate:(NSString *)date Success:(void(^)(FAMFoodrecordListModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_getUrl:getFoodmateFoodrecord parameters:nil success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        NSMutableArray *breakfastArray = [NSMutableArray array];
        NSMutableArray *lunchArray = [NSMutableArray array];
        NSMutableArray *dinnerArray = [NSMutableArray array];
        NSMutableArray *extraArray = [NSMutableArray array];
        for (int i = 0 ; i < ((NSArray *)requestDic).count; i++) {
            NSDictionary *dic = requestDic[i];
            if ([[NSString stringWithFormat:@"%@",dic[@"cate_type"]] isEqualToString:@"1"]) {
                [breakfastArray addObject:dic];
            }else if ([[NSString stringWithFormat:@"%@",dic[@"cate_type"]] isEqualToString:@"2"]){
                [lunchArray addObject:dic];
            }else if ([[NSString stringWithFormat:@"%@",dic[@"cate_type"]] isEqualToString:@"3"]){
                [dinnerArray addObject:dic];
            }else{
                [extraArray addObject:dic];
            }
        }
        [dataDic setValue:breakfastArray forKey:@"breakfast"];
        [dataDic setValue:lunchArray forKey:@"lunch"];
        [dataDic setValue:dinnerArray forKey:@"dinner"];
        [dataDic setValue:extraArray forKey:@"extra"];
        if (success) {
            success([FAMFoodrecordListModel mj_objectWithKeyValues:dataDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    } targetType:date];
}
+ (void)FAM_PutFoodmateUserdataWithParameters:(NSMutableDictionary *)parameters success:(void(^)(FAMFoodmateUserdataModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_putUrl:putFoodmateUserdata parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodmateUserdataModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}
+ (void)FAM_GetFoodmateUserdata:(void(^)(FAMGetFoodmateUserdataModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_getUrl:getFoodmateUserdata parameters:nil success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMGetFoodmateUserdataModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    } targetType:0];
}
+ (void)FAM_GetFoodmateSuggestWithParameters:(NSMutableDictionary *)parameters targetType:(NSString *)targetType success:(void(^)(FAMFoodmateUserdataModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_getUrl:foodmateSuggest parameters:nil success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodmateUserdataModel mj_objectWithKeyValues:@{@"suggestList":requestDic}],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    } targetType:targetType];
}
+ (void)FAM_PostFoodmateUserdataWithParameters:(NSMutableDictionary *)parameters  success:(void(^)(FAMFoodmateUserdataModel *,NSString *))success failure:(FailureBlock)failure{
    [[self alloc]FAM_postUrl:foodmateUserdata parameters:parameters success:^(id  _Nonnull requestDic, NSString * _Nonnull msg) {
        if (success) {
            success([FAMFoodmateUserdataModel mj_objectWithKeyValues:requestDic],nil);
        }
    } failure:^(NSString * _Nonnull errorInfo) {
        if (failure) {
            failure(errorInfo);
        }
    }];
}

- (void)FAM_uploadUrl:(NSString *)urlString parameters:(UIImage *)fileImage success:(SuccessBlock)success failure:(FailureBlock)failure{
//    NSString *url;
//    if ([urlString isEqualToString:foodmateUpload]) {
//        url = [NSString stringWithFormat:@"%@%@",FAMUpLoadImageUrl,urlString];
//    }
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
//    [request setHTTPMethod:@"POST"];
//    [request setTimeoutInterval:60];
//    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",[FAMTool FAM_getUUID]] forHTTPHeaderField:@"Content-Type"];
//    self.tempNowTime = [FAMTool FAM_getNowTimeTimestamp];
//    [request setValue:[FAMTool FAM_getAppId] forHTTPHeaderField:@"app_id"];
//    [request setValue:self.tempNowTime forHTTPHeaderField:@"rts"];
//    [request setValue:[self getEncrypRTS:nil] forHTTPHeaderField:@"encrypt"];
//    NSData *imageData = UIImageJPEGRepresentation(fileImage, 0.1);
//    NSString *fileName = [NSString stringWithFormat:@"%@.png", self.tempNowTime];
//    NSMutableData* requestMutableData = [NSMutableData data];
//    NSMutableString* myString = [NSMutableString stringWithFormat:@"boundary-%@\r\n",[FAMTool FAM_getUUID]];
//    [myString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",fileName]];
//    [myString appendString:@"Content-Type: image/jpeg\r\n\r\n"];
//    [requestMutableData appendData:[myString dataUsingEncoding:NSUTF8StringEncoding]];
//    [requestMutableData appendData:imageData];
//    request.HTTPBody = requestMutableData;
//    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//    sessionConfig.timeoutIntervalForRequest = 20;
//    NSURLSession* session  = [NSURLSession sessionWithConfiguration:sessionConfig
//                                                            delegate:self
//                                                       delegateQueue:nil];
//    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        NSString * dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//        NSDictionary * tempDic = [self parseJSONStringToNSDictionary:dataString];
//        if ([[NSString stringWithFormat:@"%@",tempDic[@"code"]] isEqualToString:@"0"]) {
//            if (tempDic[@"data"] != [NSNull new] && tempDic[@"data"] != nil ) {
//                NSDictionary *dataDic =[self parseJSONStringToNSDictionary:[FAMEncryptTool decryptWithContent:tempDic[@"data"]]];
//                if (success) {
//                    success(dataDic,@"");
//                }
//            }else{
//                if (success) {
//                    success(tempDic,@"");
//                }
//            }
//
//        }else{
//            if (failure) {
//                failure(tempDic[@"code"]);
//            }
//        }
//    }];
//    [uploadTask resume];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
//    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"application/octet-stream",@"image/jpeg",@"image/png",@"text/plain",@"text/javascript",@"multipart/form-data", nil];
    session.requestSerializer.timeoutInterval =  kTimeoutInterval;
    self.tempNowTime = [FAMTool FAM_getNowTimeTimestamp];
    NSDictionary *headers = @{
        @"app_id":[FAMTool FAM_getAppId],
        @"Content-Type":[NSString stringWithFormat:@"multipart/form-data; boundary=--%@",[FAMTool FAM_getUUID]],
        @"rts":self.tempNowTime,
        @"encrypt":[self getEncrypRTS:nil],
    };
    NSString *url;
    if ([urlString isEqualToString:foodmateUpload]) {
        url = [NSString stringWithFormat:@"%@%@",FAMUpLoadImageUrl,urlString];
    }
    NSLog(@"%@",url);
    [session POST:url parameters:nil headers:headers constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(fileImage, 0.5);
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", self.tempNowTime];
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/*"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress---->%0.2f",((float)uploadProgress.completedUnitCount)/((float)uploadProgress.totalUnitCount));
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * dataString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary * tempDic = [self parseJSONStringToNSDictionary:dataString];
        if ([[NSString stringWithFormat:@"%@",tempDic[@"code"]] isEqualToString:@"0"]) {
            if (tempDic[@"data"] != [NSNull new] && tempDic[@"data"] != nil ) {
                NSDictionary *dataDic =[self parseJSONStringToNSDictionary:[FAMEncryptTool decryptWithContent:tempDic[@"data"]]];
                if (success) {
                    success(dataDic,@"");
                }
            }else{
                if (success) {
                    success(tempDic,@"");
                }
            }
            
        }else{
            if (failure) {
                failure(tempDic[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(@"Network abnormality, please try again later");
        }
    }];
}
- (void)FAM_deleteUrl:(NSString *)urlString parameters:(NSString *)parameters success:(SuccessBlock)success failure:(FailureBlock)failure{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    session.requestSerializer.timeoutInterval =  kTimeoutInterval;
    self.tempNowTime = [FAMTool FAM_getNowTimeTimestamp];
    NSDictionary *headers = @{
        @"app_id":[FAMTool FAM_getAppId],
        @"Content-Type":@"application/json",
        @"rts":self.tempNowTime,
        @"encrypt":[self getEncrypRTS:nil],
    };
    NSString *url;
    if ([urlString isEqualToString:deleteFoodmateFoodrecord]) {
        url = [NSString stringWithFormat:@"%@%@/%@",FAMBaseUrl,urlString,parameters];
    }
    NSLog(@"%@",url);
    [session DELETE:url parameters:nil headers:headers success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * dataString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary * tempDic = [self parseJSONStringToNSDictionary:dataString];
        if ([[NSString stringWithFormat:@"%@",tempDic[@"code"]] isEqualToString:@"0"]) {
            if (tempDic[@"data"] != [NSNull new] && tempDic[@"data"] != nil ) {
                NSDictionary *dataDic =[self parseJSONStringToNSDictionary:[FAMEncryptTool decryptWithContent:tempDic[@"data"]]];
                if (success) {
                    success(dataDic,@"");
                }
            }else{
                if (success) {
                    success(tempDic,@"");
                }
            }
            
        }else{
            if (failure) {
                failure(tempDic[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(@"Network abnormality, please try again later");
        }
    }];
}

- (void)FAM_getUrl:(NSString *)urlString parameters:(NSMutableDictionary *)parameters success:(SuccessBlock)success failure:(FailureBlock)failure targetType:(NSString *)targetType{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    session.requestSerializer.timeoutInterval =  kTimeoutInterval;
    self.tempNowTime = [FAMTool FAM_getNowTimeTimestamp];
    NSDictionary *headers = @{
        @"app_id":[FAMTool FAM_getAppId],
        @"Content-Type":@"application/json",
        @"rts":self.tempNowTime,
        @"encrypt":[self getEncrypRTS:parameters],
    };
    NSString *url;
    if ([urlString isEqualToString:foodmateSuggest]) {
        url = [NSString stringWithFormat:@"%@%@?target_type=%@",FAMBaseUrl,urlString,targetType];
    }else if ([urlString isEqualToString:getFoodmateUserdata]){
        url = [NSString stringWithFormat:@"%@%@",FAMBaseUrl,urlString];
    }else if ([urlString isEqualToString:getFoodmateFoodrecord]){
        url = [NSString stringWithFormat:@"%@%@?fmt_date=%@",FAMBaseUrl,urlString,targetType];
    }else if ([urlString isEqualToString:getFoodmateStatistics]){
        NSArray *stringArray = [targetType componentsSeparatedByString:@"/"];
        url = [NSString stringWithFormat:@"%@%@?begin_date=%@&end_date=%@",FAMBaseUrl,urlString,stringArray[0],stringArray[1]];
    }
    NSLog(@"%@",url);
    [session GET:url parameters:nil headers:headers progress:^(NSProgress * _Nonnull downloadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * dataString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary * tempDic = [self parseJSONStringToNSDictionary:dataString];
        if ([[NSString stringWithFormat:@"%@",tempDic[@"code"]] isEqualToString:@"0"]) {
            NSDictionary *dataDic =[self parseJSONStringToNSDictionary:[FAMEncryptTool decryptWithContent:tempDic[@"data"]]];
            if (success) {
                success(dataDic,@"");
            }
        }else{
            if (failure) {
                failure(tempDic[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(@"Server problem");
        }
    }];
}

- (void)FAM_putUrl:(NSString *)urlString parameters:(NSMutableDictionary *)parameters  success:(SuccessBlock)success failure:(FailureBlock)failure{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    session.requestSerializer.timeoutInterval =  kTimeoutInterval;
    self.tempNowTime = [FAMTool FAM_getNowTimeTimestamp];
    NSDictionary *headers = @{
        @"app_id":[FAMTool FAM_getAppId],
        @"Content-Type":@"application/json",
        @"rts":self.tempNowTime,
        @"encrypt":[self getEncrypRTS:nil],
    };
    NSString *url;
    NSMutableDictionary *tempParameters;
    if ([urlString isEqualToString:putFoodmateUserdata]) {
        url = [NSString stringWithFormat:@"%@%@?fmt_date=%@",FAMBaseUrl,urlString,[FAMTool FAM_getYearWithMonthWithDay]];
    }else if([urlString isEqualToString:putFoodmateFoodrecord]){
        url = [NSString stringWithFormat:@"%@%@",FAMBaseUrl,urlString];
    }
    tempParameters = [NSMutableDictionary dictionaryWithDictionary:[self getEncryBody:parameters[@"data"] isArray:NO]];
    session.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    [session PUT:url parameters:tempParameters headers:headers success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * dataString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary * tempDic = [self parseJSONStringToNSDictionary:dataString];
        if ([[NSString stringWithFormat:@"%@",tempDic[@"code"]] isEqualToString:@"0"]) {
            if (tempDic[@"data"] != [NSNull new] && tempDic[@"data"] != nil ) {
                NSDictionary *dataDic =[self parseJSONStringToNSDictionary:[FAMEncryptTool decryptWithContent:tempDic[@"data"]]];
                if (success) {
                    success(dataDic,@"");
                }
            }else{
                if (success) {
                    success(tempDic,@"");
                }
            }
            
        }else{
            if (failure) {
                failure(tempDic[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        if (failure) {
            failure(@"Network abnormality, please try again later");
        }
    }];
}

- (void)FAM_postUrl:(NSString *)urlString parameters:(NSMutableDictionary *)parameters success:(SuccessBlock)success failure:(FailureBlock)failure{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", nil];
    session.requestSerializer.timeoutInterval =  kTimeoutInterval;
    self.tempNowTime = [FAMTool FAM_getNowTimeTimestamp];
    NSDictionary *headers = @{
        @"app_id":[FAMTool FAM_getAppId],
        @"Content-Type":@"application/json",
        @"rts":self.tempNowTime,
        @"encrypt":[self getEncrypRTS:nil],
    };
    NSString *url;
    NSMutableDictionary *tempParameters;
    if ([urlString isEqualToString:foodmateUserdata]) {
        url = [NSString stringWithFormat:@"%@%@?fmt_date=%@",FAMBaseUrl,urlString,[FAMTool FAM_getYearWithMonthWithDay]];
    }else if ([urlString isEqualToString:postFoodmateFoodrecord]){
        url = [NSString stringWithFormat:@"%@%@",FAMBaseUrl,urlString];
    }else if ([urlString isEqualToString:foodIdentify]){
        url = [NSString stringWithFormat:@"%@%@",FAMBaseUrl,urlString];
    }else if([urlString isEqualToString:foodReidentify]){
        url = [NSString stringWithFormat:@"%@%@",FAMBaseUrl,urlString];
    }else if ([urlString isEqualToString:foodRecordBatch]){
        url = [NSString stringWithFormat:@"%@%@",FAMBaseUrl,urlString];
    }
    
    tempParameters = [NSMutableDictionary dictionaryWithDictionary:[self getEncryBody:parameters[@"data"] isArray:NO]];
    NSLog(@"%@",url);
    session.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    [session POST:url parameters:tempParameters headers:headers progress:^(NSProgress * _Nonnull uploadProgress) {
            
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * dataString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary * tempDic = [self parseJSONStringToNSDictionary:dataString];
        if ([[NSString stringWithFormat:@"%@",tempDic[@"code"]] isEqualToString:@"0"]) {
            if (tempDic[@"data"] != [NSNull new] && tempDic[@"data"] != nil ) {
                NSDictionary *dataDic =[self parseJSONStringToNSDictionary:[FAMEncryptTool decryptWithContent:tempDic[@"data"]]];
                if (success) {
                    success(dataDic,@"");
                }
            }else{
                if (success) {
                    success(tempDic,@"");
                }
            }
            
        }else{
            if (failure) {
                failure(tempDic[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",task);
        NSLog(@"%@",error);
        if (failure) {
            failure(@"Network abnormality, please try again later");
        }
    }];
}

- (NSString *)getEncrypRTS:(NSMutableDictionary *)params {
    NSMutableDictionary *additionalParameters = [self FAM_fillParams:params];
    NSString *sign = [[[FAMMD5 alloc]MD5:[AIRequestTool calculateSignValue:additionalParameters appKey:[FAMTool FAM_getAppKey]]] lowercaseString];
    additionalParameters[@"sign"] = sign;
    return [FAMEncryptTool encryptWithContent:additionalParameters];
}
- (NSDictionary *)getEncryBody:(NSMutableDictionary *)params isArray:(BOOL) isArray{
    NSMutableDictionary *additionalParameters = [[NSMutableDictionary alloc]init];
    additionalParameters[@"rts"] = self.tempNowTime;
    if (isArray) {
        additionalParameters[@"data"] = [FAMEncryptTool convertToJSONStringWithObject:@[params]];
    }else{
        additionalParameters[@"data"] = [FAMEncryptTool convertToJSONStringWithObject:params];
    }
    NSString *sign = [[[FAMMD5 alloc]MD5:[AIRequestTool calculateSignValue:additionalParameters appKey:[FAMTool FAM_getAppKey]]] lowercaseString];
    additionalParameters[@"sign"] = sign;
    return @{@"data":[FAMEncryptTool encryptWithContent:additionalParameters]};
}
- (NSMutableDictionary *)FAM_fillParams:(NSMutableDictionary *)temp{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[FAM_OCString(_2753689520)] = [FAMTool FAM_getUUID];
    parameters[FAM_OCString(_475199832)] = [FAMTool FAM_getDeviceBrand];
    parameters[FAM_OCString(_1574768987)] = [AIRequestTool curAppVersion];
    parameters[FAM_OCString(_822707298)] = [FAMTool FAM_getCurrentLanguage];
    parameters[FAM_OCString(_711719256)] = self.tempNowTime;
    parameters[FAM_OCString(_1837722535)] = @"wifi";
    parameters[FAM_OCString(_3616895705)] = [FAMTool FAM_getDeviceModel];
    parameters[FAM_OCString(_675401137)] = [AIRequestTool curAppVersion];
    parameters[FAM_OCString(_2027889517)] = @"1.0.0";
    parameters[FAM_OCString(_2560028841)] = [AIRequestTool getBundleIdentifier];
    parameters[FAM_OCString(_1961582533)] = [AIRequestTool getBundleVersion];
    parameters[FAM_OCString(_675401137)] = [FAMTool  FAM_getOSCode];
    parameters[FAM_OCString(_822707298)] = @"en";
    NSArray *dictKeysArray = [temp allKeys];
    for (int i = 0; i<dictKeysArray.count; i++) {
        NSString *key = dictKeysArray[i];
        NSString *value = [temp objectForKey:key];
        parameters[key] = value;
    }
    return parameters;
}
-(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
@end
